﻿using ERPWinFormWork.Produce.Domain;
using ERPWinFormWork.Produce.ErrorCode;
using ERPWinFormWork.Produce.Produce.Dtos;
using ERPWinFormWork.Product.ProductErrorCode;
using ERPWinFormWork.Sales;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ERPWinFormWork.Produce.CreateProduction_Plan;

namespace ERPWinFormWork.Produce
{
    public partial class Work_TaskFrom : Form
    {

        private ApiClient _apiClient;
        // 标识窗口内的核心方法是否执行完成
        public bool IsOperationCompleted { get; private set; } = false;
        

        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalPages { get; set; } = 1;
        private int TotalSize { get; set; }

        public Work_TaskFrom()
        {
            InitializeComponent();
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            GetData();
            LoadProcess_NameData();
            LoadcboStateData();
          
            dgvWork_TaskData.CellFormatting += dgvWork_TaskData_CellFormatting; // Add CellFormatting to display state as text
        }
        // 如果用户取消操作，标识保持为false
        private void btnCancel_Click(object sender, EventArgs e)
        {
            IsOperationCompleted = false;
            this.Close();
        }


        private async void GetData()
        {
            // 获取状态值（1-4），默认为0（表示全部）
            int stateValue = 0;
            if (cboState.SelectedItem != null && cboState.SelectedValue != null)
            {
                int.TryParse(cboState.SelectedValue.ToString(), out stateValue);
            }

            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Task", this.txtTask.Text.Trim()},
                    { "Work_Number", this.txtWork_Number.Text.Trim() },
                    { "Process_Name", this.cboProcess_Name.Text.Trim() },
                   { "State", stateValue.ToString()},
                   

                };
            var response = await _apiClient.GetAsync<ApiResponse<List<Work_Task>>>(
                    endpoint: "Production_Plan/GetWork_TaskHandle",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvWork_TaskData.DataSource = response.pageData;
                TotalPages = response.totalCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblcount.Text = TotalSize.ToString();
                AddOperationColumns();

                // 添加序号列作为第一列
                if (dgvWork_TaskData.Columns["SerialNo"] == null)
                {
                    DataGridViewTextBoxColumn serialCol = new DataGridViewTextBoxColumn();
                    serialCol.Name = "SerialNo";
                    serialCol.HeaderText = "序号";
                    serialCol.ReadOnly = true;
                    dgvWork_TaskData.Columns.Insert(0, serialCol); // 插入为第一列
                }

                // 填充序号（全局索引，正序）
                for (int i = 0; i < dgvWork_TaskData.Rows.Count; i++)
                {
                    int serial = (PageIndex - 1) * PageSize + i + 1;
                    dgvWork_TaskData.Rows[i].Cells["SerialNo"].Value = serial;
                }

                // 隐藏Id列
                if (dgvWork_TaskData.Columns["Id"] != null)
                {
                    dgvWork_TaskData.Columns["Id"].Visible = false;
                }
            }

        }

        private void AddOperationColumns()
        {
            string[] columnNames = { "Dispatch", "Start", "Report" };
            string[] headerTexts = { "派工", "开工", "报工" };


            for (int i = 0; i < columnNames.Length; i++)
            {
                if (dgvWork_TaskData.Columns[columnNames[i]] == null)
                {
                    var col = new DataGridViewButtonColumn();
                    col.Name = columnNames[i];
                    col.HeaderText = headerTexts[i];
                    col.Text = headerTexts[i];
                    col.UseColumnTextForButtonValue = true;
                    dgvWork_TaskData.Columns.Add(col);
                }
            }
        }
        private async void dgvWork_TaskData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                Work_Task item = dgvWork_TaskData.Rows[e.RowIndex].DataBoundItem as Work_Task;
                if (item != null)
                {
                    string colName = dgvWork_TaskData.Columns[e.ColumnIndex].Name;
                    if (colName == "Dispatch")
                    {
                        Dispatch_WorkForm form1 = new Dispatch_WorkForm();
                        form1.ShowDialog();
                        if (form1.IsOperationCompleted)
                        {
                            var data = new { id = item.Id, state = 2 };
                            var response = await _apiClient.PostAsync<object, ApiResponse<string>>("Production_Plan/DispatchworkHandle", data);

                            if (response != null && response.code == 200)
                            {
                                MessageBox.Show("已修改为派工状态", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                GetData();
                            }
                            else
                            {
                                MessageBox.Show($"派工状态修改失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }

                           
                    }
                    else if (colName == "Start")
                    {
                        var data = new { id = item.Id, state = 3 };
                        var response = await _apiClient.PostAsync<object, ApiResponse<string>>("Production_Plan/DispatchworkHandle", data);
                        if (response != null && response.code == 200)
                        {
                            MessageBox.Show("开工成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            GetData();
                        }
                        else
                        {
                            MessageBox.Show($"开工失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else if (colName == "Report")
                    {
                        Reporting_WorkFrom form1 = new Reporting_WorkFrom();
                        form1.ShowDialog();
                        if (form1.IsOperationCompleteds)
                        {
                            var data = new { id = item.Id, state = 4 };
                            var response = await _apiClient.PostAsync<object, ApiResponse<string>>("Production_Plan/DispatchworkHandle", data);

                            if (response != null && response.code == 200)
                            {
                                MessageBox.Show("已修改为报工状态", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                GetData();
                            }
                            else
                            {
                                MessageBox.Show($"报工状态修改失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
        }

        public class UpstateStetaDispatch_Work
        {
            public int Id { get; set; }
            /// <summary>
            /// 状态
            /// </summary>
            public int State { get; set; }
        }
       






        private void LoadProcess_NameData()
        {
            // 模拟一个数据源，这里是简单的字符串列表，实际可从数据库等获取
            List<string> addressList = new List<string>()
            {
                "工序一",
                "工序二",
                "工序三",
                "工序四",
                
            };

            // 清空ComboBox原有项（可选，避免重复添加）
            cboProcess_Name.Items.Clear();
            // 将数据源的数据添加到ComboBox中
            cboProcess_Name.Items.AddRange(addressList.ToArray());

            // 可选：设置默认选中项，比如选第一个
            if (cboProcess_Name.Items.Count > 0)
            {
                cboProcess_Name.SelectedIndex = -1;
            }
        }

        private void cboProcess_Name_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboProcess_Name.SelectedItem != null)
            {
                string selectedAddress = cboProcess_Name.SelectedItem.ToString();
                
            }
        }
        private void LoadcboStateData()
        {
            // 创建包含显示文本和对应值的数据源
            var stateList = new List<object>()
    {
        new { Text = "未派工", Value = 1 },
        new { Text = "已下达", Value = 2 },
        new { Text = "进行中", Value = 3 },
        new { Text = "未质检", Value = 4 },
        new { Text = "已质检", Value = 5 }
    };

            // 清空ComboBox原有项
            cboState.Items.Clear();

            // 设置数据源
            cboState.DataSource = stateList;
            // 设置显示的文本字段
            cboState.DisplayMember = "Text";
            // 设置对应的值字段
            cboState.ValueMember = "Value";

            // 不设置默认选中项
            cboState.SelectedIndex = -1;
        }
        private void cboState_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboState.SelectedItem != null)
            {
                string selectedAddress = cboState.SelectedItem.ToString();

            }
        }

        private void btnGetWhere_Click(object sender, EventArgs e)
        {
            GetData();
        }

        private void btnreset_Click(object sender, EventArgs e)
        {
            txtTask.Clear();
            txtWork_Number.Clear();
           cboState.SelectedIndex = -1;
            cboProcess_Name.SelectedIndex = -1;
            GetData();
        }

        private void btnPreviousPage_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        private void btnNextpage_Click(object sender, EventArgs e)
        {
            if (PageIndex < TotalSize)
            {
                PageIndex++;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        private void txtTask_TextChanged(object sender, EventArgs e)
        {

        }

        // Add CellFormatting event handler to format State column
        private void dgvWork_TaskData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvWork_TaskData.Columns[e.ColumnIndex].Name == "State" && e.Value != null)
            {
                int state = Convert.ToInt32(e.Value);
                switch (state)
                {
                    case 1: e.Value = "未派工"; break;
                    case 2: e.Value = "已下达"; break;
                    case 3: e.Value = "进行中"; break;
                    case 4: e.Value = "未质检"; break;
                    case 5: e.Value = "已质检"; break;
                    default: e.Value = "未知"; break;
                }
            }
        }
    }
}
